import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Typography, 
  Tag, 
  Rate, 
  Divider, 
  Button, 
  Tabs, 
  Table, 
  Space, 
  Modal, 
  Select, 
  Form, 
  Input,
  InputNumber, 
  message, 
  Spin,
  Avatar,
  List,
  Tooltip,
  Card,
  Empty
} from 'antd';
import { 
  ClockCircleOutlined, 
  EnvironmentOutlined, 
  CalendarOutlined, 
  TeamOutlined,
  UserOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import axios from 'axios';
import '../styles/MovieDetail.css';
import MovieService from '../services/MovieService';
import CommentService from '../services/CommentService';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;

// Mock movie details
const mockMovies = {
  '1': {
    id: 1,
    title: '流浪地球2',
    originalTitle: 'The Wandering Earth 2',
    posterUrl: 'https://n.sinaimg.cn/sinakd20230123s/706/w1906h2800/20230123/9137-b383634783de89cde4d98c83c618be19.jpg',
    backdropUrl: 'https://img2.doubanio.com/view/photo/l/public/p2885955777.jpg',
    releaseDate: '2023-01-22',
    durationMinutes: 173,
    director: '郭帆',
    cast: '吴京, 刘德华, 李雪健, 沙溢, 宁理, 王智',
    synopsis: '在不远的未来，太阳即将毁灭，人类在地球表面建造出巨大的推进器，寻找新的家园。然而宇宙之路危机四伏，为了拯救地球，流浪地球时代的年轻人再次挺身而出，展开争分夺秒的生死之战。',
    language: '中文',
    country: '中国',
    rating: 8.3,
    status: 'RELEASED',
    categories: ['科幻', '冒险', '灾难']
  },
  '2': {
    id: 2,
    title: '满江红',
    originalTitle: 'Full River Red',
    posterUrl: 'https://img2.jiemian.com/101/original/20230125/167457861579568000_a700xH.jpeg',
    backdropUrl: 'https://img2.jiemian.com/101/original/20230125/167457861579568000_a700xH.jpeg',
    releaseDate: '2023-01-22',
    durationMinutes: 159,
    director: '张艺谋',
    cast: '沈腾, 易烊千玺, 张译, 雷佳音, 岳云鹏',
    synopsis: '南宋绍兴年间，岳飞死后四年，秦桧率领南宋使团进入金营议和。一份价值连城的和议文书即将大皇宫。临行前夜，使团中的一名将士在宿处离奇死亡，而和议文书也不翼而飞。负责缉查的御前侍卫郭独胜（沈腾 饰）和金牌第一捕头孙均（易烊千玺 饰）需要在天亮前找到真相，否则整个使团将面临灭顶之灾。',
    language: '中文',
    country: '中国',
    rating: 8.1,
    status: 'RELEASED',
    categories: ['悬疑', '剧情', '古装']
  },
  '3': {
    id: 3,
    title: '奇迹笨小孩',
    originalTitle: 'Nice View',
    posterUrl: 'https://img9.doubanio.com/view/photo/l/public/p2869051133.jpg',
    backdropUrl: 'https://img9.doubanio.com/view/photo/l/public/p2869051133.jpg',
    releaseDate: '2022-02-01',
    durationMinutes: 106,
    director: '文牧野',
    cast: '易烊千玺, 田雨, 陈哈哈, 孙阳, 韩东君',
    synopsis: '一个出身不好却想要出人头地的年轻人，一个被生活压得喘不过气却依然不放弃的打工人，一个自以为是的富二代，一个单纯的大学生。多个人物的命运交错，在这座充满机遇又残酷的城市里，追逐着各自的梦想。',
    language: '中文',
    country: '中国',
    rating: 7.3,
    status: 'RELEASED',
    categories: ['剧情', '家庭']
  },
  '4': {
    id: 4,
    title: '唐探1900',
    originalTitle: 'Detective Chinatown 1900',
    posterUrl: 'https://img9.doubanio.com/view/photo/l/public/p2888333780.jpg',
    backdropUrl: 'https://img9.doubanio.com/view/photo/l/public/p2888333780.jpg',
    releaseDate: '2024-02-10',
    durationMinutes: 128,
    director: '陈思诚',
    cast: '王宝强, 刘昊然, 张子枫, 黄渤, 马伊琍',
    synopsis: '故事发生在1900年的上海。唐仁（王宝强 饰）和秦风（刘昊然 饰）受邀来到上海滩调查一起离奇命案。在这个华洋杂处的十里洋场，他们遇到了来自世界各地的侦探高手，并卷入了一场关乎上海滩命运的惊天谜案。在解开谜题的过程中，他们不仅要面对神秘对手的层层设局，更要直面那段动荡年代里的历史暗流。',
    language: '中文',
    country: '中国',
    rating: 8.5,
    status: 'UPCOMING',
    categories: ['喜剧', '悬疑', '动作']
  },
  '5': {
    id: 5,
    title: '铃芽之旅',
    originalTitle: 'Suzume no Tojimari',
    posterUrl: 'https://img9.doubanio.com/view/photo/l/public/p2885955777.jpg',
    backdropUrl: 'https://img9.doubanio.com/view/photo/l/public/p2885955777.jpg',
    releaseDate: '2023-03-24',
    durationMinutes: 122,
    director: '新海诚',
    cast: '原菜乃华, 松村北斗, 深津绘里, 染谷将太',
    synopsis: '在日本各地陆续发现了带来灾厄的神秘门扉。为了解开这一谜团，铃芽踏上了一段奇妙的冒险之旅。在这个现代童话里，"关门"成为了拯救日本面临的一场灾难的关键。',
    language: '日语',
    country: '日本',
    rating: 8.2,
    status: 'RELEASED',
    categories: ['动画', '奇幻', '冒险']
  }
};

// Mock screenings
const mockScreenings = [
  {
    id: 1,
    startTime: '2023-05-15 10:00:00',
    endTime: '2023-05-15 12:00:00',
    price: 35.0,
    hallName: '1号厅',
    cinemaName: '星光影院',
    availableSeats: 80
  },
  {
    id: 2,
    startTime: '2023-05-15 13:00:00',
    endTime: '2023-05-15 15:00:00',
    price: 35.0,
    hallName: '2号厅',
    cinemaName: '星光影院',
    availableSeats: 65
  },
  {
    id: 3,
    startTime: '2023-05-15 16:00:00',
    endTime: '2023-05-15 18:00:00',
    price: 45.0,
    hallName: '1号厅',
    cinemaName: '环球影院',
    availableSeats: 50
  },
  {
    id: 4,
    startTime: '2023-05-15 19:00:00',
    endTime: '2023-05-15 21:00:00',
    price: 45.0,
    hallName: 'IMAX厅',
    cinemaName: '环球影院',
    availableSeats: 25
  }
];

// Mock reviews
const mockReviews = [
  {
    id: 1,
    username: '用户1',
    rating: 4.5,
    comment: '很棒的电影，画面很精美，剧情也很紧凑，推荐观看！',
    createdAt: '2023-05-02'
  },
  {
    id: 2,
    username: '用户2',
    rating: 3.0,
    comment: '还行吧，剧情有些地方不太合理，但是整体来说值得一看。',
    createdAt: '2023-05-03'
  },
  {
    id: 3,
    username: '用户3',
    rating: 5.0,
    comment: '太精彩了！这是今年看过的最好的电影，没有之一！',
    createdAt: '2023-05-04'
  }
];

const MovieDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [movie, setMovie] = useState(null);
  const [screenings, setScreenings] = useState([]);
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [ticketModalVisible, setTicketModalVisible] = useState(false);
  const [selectedScreening, setSelectedScreening] = useState(null);
  const [form] = Form.useForm();
  const [commentForm] = Form.useForm();
  const [commentSubmitting, setCommentSubmitting] = useState(false);
  const isLoggedIn = localStorage.getItem('token') !== null;
  const username = localStorage.getItem('username') || '匿名用户';

  useEffect(() => {
    const fetchMovieData = async () => {
      try {
        setLoading(true);
        
        // 使用mockMovies数据替代API调用
        const movieData = mockMovies[id];
        if (!movieData) {
          message.error('电影不存在');
          navigate('/movies');
          return;
        }
        setMovie(movieData);
        
        // 使用现有的模拟数据
        setScreenings(mockScreenings);
        setReviews(mockReviews);
        
        setLoading(false);
      } catch (error) {
        console.error('Error fetching movie data:', error);
        message.error('获取电影数据失败，请重试');
        setLoading(false);
      }
    };

    fetchMovieData();
  }, [id, navigate]);

  const handleBooking = (screening) => {
    if (!isLoggedIn) {
      message.warning('请先登录再购票');
      return;
    }
    
    // 使用 React Router 导航到选座页面，并传递 screeningId
    navigate(`/screening/${screening.id}/select-seats`, {
      state: {
        movie: movie,
        screening: screening
      }
    });
  };

  const handleBookingSubmit = (values) => {
    // In a real app, send booking request to the server
    // Example:
    // axios.post('/api/bookings', values)
    //   .then(response => {
    //     message.success('订票成功');
    //     setTicketModalVisible(false);
    //   })
    //   .catch(error => {
    //     message.error(error.response?.data?.message || '订票失败，请重试');
    //   });
    
    // Simulate API call
    setTimeout(() => {
      message.success('订票成功');
      setTicketModalVisible(false);
    }, 1500);
  };

  const formatDateTime = (dateTimeStr) => {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
      month: 'numeric',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric'
    });
  };

  const screeningColumns = [
    {
      title: '放映时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (text) => formatDateTime(text)
    },
    {
      title: '影院',
      dataIndex: 'cinemaName',
      key: 'cinemaName'
    },
    {
      title: '影厅',
      dataIndex: 'hallName',
      key: 'hallName'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (text) => `¥${text.toFixed(2)}`
    },
    {
      title: '剩余座位',
      dataIndex: 'availableSeats',
      key: 'availableSeats'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          onClick={() => {
            if (!isLoggedIn) {
              message.warning('请先登录再购票');
              navigate('/login');
              return;
            }
            navigate(`/screening/${record.id}/select-seats`, {
              state: {
                movie,
                screening: record
              }
            });
          }}
        >
          选座购票
        </Button>
      ),
    },
  ];

  const handleCommentSubmit = async (values) => {
    if (!isLoggedIn) {
      message.warning('请先登录后再发表评论');
      return;
    }

    try {
      setCommentSubmitting(true);
      
      // 提交评论数据
      const commentData = {
        rating: values.rating,
        comment: values.comment
      };
      
      const response = await CommentService.addMovieComment(id, commentData);
      
      // 添加新评论到评论列表
      setReviews([response.data, ...reviews]);
      
      // 重置表单
      commentForm.resetFields();
      
      message.success('评论发表成功');
    } catch (error) {
      console.error('Error submitting comment:', error);
      message.error('评论发表失败，请重试');
    } finally {
      setCommentSubmitting(false);
    }
  };

  const handleDeleteComment = async (commentId) => {
    try {
      await CommentService.deleteMovieComment(commentId);
      
      // 从评论列表中移除已删除的评论
      setReviews(reviews.filter(review => review.id !== commentId));
      
      message.success('评论已删除');
    } catch (error) {
      console.error('Error deleting comment:', error);
      message.error('删除评论失败，请重试');
    }
  };

  const renderCommentList = () => {
    return (
      <div className="comments-section">
        {isLoggedIn && (
          <Card className="comment-form-card">
            <Form
              form={commentForm}
              onFinish={handleCommentSubmit}
              layout="vertical"
            >
              <Form.Item
                name="rating"
                label="评分"
                rules={[{ required: true, message: '请为电影评分' }]}
              >
                <Rate allowHalf />
              </Form.Item>
              <Form.Item
                name="comment"
                label="评论"
                rules={[{ required: true, message: '请输入您的评论' }]}
              >
                <TextArea rows={4} placeholder="分享您对这部电影的看法..." />
              </Form.Item>
              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={commentSubmitting}
                >
                  发表评论
                </Button>
              </Form.Item>
            </Form>
          </Card>
        )}

        <Divider orientation="left">用户评论 ({reviews.length})</Divider>
        
        {reviews.length > 0 ? (
          <List
            className="comment-list"
            itemLayout="horizontal"
            dataSource={reviews}
            pagination={{
              onChange: page => {
                window.scrollTo(0, document.querySelector('.comments-section').offsetTop - 100);
              },
              pageSize: 5,
              hideOnSinglePage: true,
              showSizeChanger: false,
              size: 'small'
            }}
            renderItem={review => (
              <List.Item
                key={review.id}
                actions={
                  isLoggedIn && username === review.username ? [
                    <Tooltip key="delete" title="删除评论">
                      <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteComment(review.id)}
                      />
                    </Tooltip>
                  ] : []
                }
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<UserOutlined />} />}
                  title={
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <Text strong>{review.username}</Text>
                      <Tooltip title={review.createdAt}>
                        <Text type="secondary">{review.createdAt}</Text>
                      </Tooltip>
                    </div>
                  }
                  description={
                    <div>
                      <div className="comment-rating">
                        <Rate disabled defaultValue={review.rating} allowHalf />
                        <Text style={{ marginLeft: 8 }}>{review.rating} 分</Text>
                      </div>
                      <Paragraph>{review.comment}</Paragraph>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        ) : (
          <div className="no-comments">
            <Empty description="暂无评论" />
            <Paragraph type="secondary" style={{ textAlign: 'center' }}>
              成为第一个评论这部电影的人吧！
            </Paragraph>
          </div>
        )}
        
        {!isLoggedIn && (
          <div className="login-prompt">
            <Divider />
            <Text type="secondary">
              想要发表评论？请先 
              <Button type="link" onClick={() => navigate('/login')}>
                登录
              </Button>
            </Text>
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!movie) {
    return <div>电影不存在或已下架</div>;
  }

  const statusColors = {
    UPCOMING: 'blue',
    RELEASED: 'green',
    ENDED: 'red'
  };

  return (
    <div>
      {/* Movie Header */}
      <div 
        style={{ 
          backgroundImage: `url(${movie.backdropUrl})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          padding: '40px 0',
          marginBottom: '24px',
          position: 'relative'
        }}
      >
        <div 
          style={{ 
            background: 'rgba(0,0,0,0.7)', 
            position: 'absolute', 
            top: 0, 
            left: 0, 
            right: 0, 
            bottom: 0
          }}
        />
        <div className="movie-detail-container" style={{ position: 'relative', zIndex: 1 }}>
          <div className="movie-detail-poster">
            <img src={movie.posterUrl} alt={movie.title} />
          </div>
          <div className="movie-detail-info" style={{ color: 'white' }}>
            <div className="movie-detail-title">{movie.title}</div>
            {movie.originalTitle && <div>{movie.originalTitle}</div>}
            
            <div className="movie-detail-meta" style={{ marginTop: '16px' }}>
              <Rate disabled defaultValue={movie.rating / 2} allowHalf /> 
              <span className="ant-rate-text">{movie.rating}</span>
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <Tag color={statusColors[movie.status]}>{movie.status}</Tag>
            </div>
            
            <div style={{ marginBottom: '8px' }}>
              <Space>
                <ClockCircleOutlined /> {movie.durationMinutes} 分钟
                <CalendarOutlined /> {movie.releaseDate}
              </Space>
            </div>
            
            <div style={{ marginBottom: '8px' }}>
              <Space>
                <Text style={{ color: 'white' }}>导演：{movie.director}</Text>
              </Space>
            </div>
            
            <div style={{ marginBottom: '8px' }}>
              <Space>
                <TeamOutlined /> {movie.cast}
              </Space>
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <Space>
                {movie.categories.map(category => (
                  <Tag key={category}>{category}</Tag>
                ))}
              </Space>
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <Space>
                <Text style={{ color: 'white' }}>语言：{movie.language}</Text>
                <Text style={{ color: 'white' }}>国家/地区：{movie.country}</Text>
              </Space>
            </div>
          </div>
        </div>
      </div>

      {/* Movie Details Tabs */}
      <Tabs defaultActiveKey="1" style={{ marginTop: '24px' }}>
        <TabPane tab="剧情简介" key="1">
          <Paragraph>{movie.synopsis}</Paragraph>
        </TabPane>
        
        <TabPane tab="放映场次" key="2">
          <Table 
            dataSource={screenings} 
            columns={screeningColumns} 
            rowKey="id"
            pagination={false}
          />
        </TabPane>
        
        <TabPane tab="用户评价" key="3">
          {renderCommentList()}
        </TabPane>
      </Tabs>

      {/* Ticket Booking Modal */}
      <Modal
        title="购买电影票"
        visible={ticketModalVisible}
        onCancel={() => setTicketModalVisible(false)}
        footer={null}
        className="movie-ticket-modal"
      >
        {selectedScreening && (
          <Form form={form} onFinish={handleBookingSubmit} layout="vertical">
            <Form.Item name="screeningId" hidden>
              <InputNumber />
            </Form.Item>
            
            <Form.Item label="影院">
              <Text>{selectedScreening.cinemaName}</Text>
            </Form.Item>
            
            <Form.Item label="影厅">
              <Text>{selectedScreening.hallName}</Text>
            </Form.Item>
            
            <Form.Item label="场次">
              <Text>{formatDateTime(selectedScreening.startTime)}</Text>
            </Form.Item>
            
            <Form.Item label="票价">
              <Text>¥{selectedScreening.price.toFixed(2)}</Text>
            </Form.Item>
            
            <Form.Item
              name="ticketType"
              label="票类型"
              rules={[{ required: true, message: '请选择票类型' }]}
            >
              <Select>
                <Option value="Standard">普通票</Option>
                <Option value="VIP">VIP票</Option>
                <Option value="Child">儿童票</Option>
                <Option value="Senior">老人票</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="quantity"
              label="数量"
              rules={[{ required: true, message: '请选择购票数量' }]}
            >
              <InputNumber min={1} max={10} />
            </Form.Item>
            
            <Form.Item>
              <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
                确认购买
              </Button>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default MovieDetail; 